package com.nosnow.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import com.aliyuncs.vod.model.v20170321.DeleteVideoResponse;
import com.nosnow.vod.service.VodService;
import com.nosnow.vod.utils.ConstantVideoUtils;
import com.nosnow.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/4/11 14:08
 */

@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadAlyVideo(MultipartFile file) throws Exception{

        // fileName：上传文件原始名称
        String fileName = file.getOriginalFilename();

        // title: 上传之后显示的名称(获取最后一个 .  前面的内容)
        String title = fileName.substring(0, fileName.lastIndexOf("."));

        UploadStreamRequest request = new UploadStreamRequest(ConstantVideoUtils.ACCESS_KEY_ID, ConstantVideoUtils.ACCESS_KEY_SECRET, title, fileName, file.getInputStream());

        UploadVideoImpl uploadVideo = new UploadVideoImpl();
        UploadStreamResponse response = uploadVideo.uploadStream(request);

        // 请求视频点播服务的请求Id
        String videoId = response.getVideoId();
        if(response.isSuccess()) {
            videoId = response.getVideoId();
        } else {
            // 如果设置回调url无效，不影响视频上传，可以返回video同时会返回错误码，其他情况上传失败时video为空，此时需要根据返回错误码分析具体错误原因
            videoId = response.getVideoId();
        }
        return videoId;
    }

    @Override
    public void deleteAlyVideo(String id) throws Exception {
        // 1. 初始化对象
        DefaultAcsClient client = InitVodClient.initVodClient(ConstantVideoUtils.REGION_ID, ConstantVideoUtils.ACCESS_KEY_ID, ConstantVideoUtils.ACCESS_KEY_SECRET);

        // 2. 创建删除视频的request对象
        DeleteVideoRequest request = new DeleteVideoRequest();

        // 3. 向request对象中设置视频Id, 支持多个id
        request.setVideoIds(id);

        // 4. 调用初始化对象的方法实现删除
        client.getAcsResponse(request);
    }

    @Override
    public void deleteAlyVideos(List<String> videoIdList) throws Exception {
        // 1. 初始化对象
        DefaultAcsClient client = InitVodClient.initVodClient(ConstantVideoUtils.REGION_ID, ConstantVideoUtils.ACCESS_KEY_ID, ConstantVideoUtils.ACCESS_KEY_SECRET);

        // 2. 创建删除视频的request对象
        DeleteVideoRequest request = new DeleteVideoRequest();

        // 3. 将videoIdList中的值拼接成一个字符串，并用逗号隔开
        String videoIds = StringUtils.join(videoIdList.toArray(), ",");

        // 4. 向request对象中设置视频Id, 支持多个id
        request.setVideoIds(videoIds);

        // 5. 调用初始化对象的方法实现删除
        client.getAcsResponse(request);
    }
}
